package cn.rocky.prepare;

/**
 * 2. 两数之和
 */
public class addTwoNumbers {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int j = 0;
        //结果链表虚拟头结点
        ListNode dummyNode = new ListNode(-1);
        //结果链表工作指针
        ListNode cur = dummyNode;
        while (!(l1 == null && l2 == null)) {
            int v1 = l1 == null ? 0 : l1.val;
            int v2 = l2 == null ? 0 : l2.val;
            int sum = v1 + v2 + j;
            j = sum / 10;
            sum = sum % 10;
            //新建链表结点，将val赋值为sum
            cur.next = new ListNode(sum);
            cur = cur.next;
            if (l1 != null) l1 = l1.next;
            if (l2 != null) l2 = l2.next;
        }
        //难点：最后的进位是特殊情况，需要增加新结点并赋val值为1
        if(j == 1){
            cur.next = new ListNode(1);
        }
        //返回结果链表的头结点
        return dummyNode.next;
    }
}
